import tushare as ts
import pandas as pd
import matplotlib.pyplot as plt

# 初始化 Tushare
ts.set_token('1c7f85b9026518588c0d0cdac712c2d17344332c9c8cfe6bc83ee75c')  
pro = ts.pro_api()

# 获取所有股票代码
print("正在获取所有股票代码...")
stock_list = pro.stock_basic(exchange='', list_status='L', fields='ts_code,name')

# 获取最近 10 个交易日的日期范围
print("正在获取最近 10 个交易日的日期范围...")
trade_cal = pro.trade_cal(exchange='', start_date='20230301', end_date='20230331', is_open='1')
recent_10_trading_days = trade_cal['cal_date'].tail(10).tolist()
start_date = recent_10_trading_days[0]
end_date = recent_10_trading_days[-1]

# 获取所有股票的日线数据
def get_all_stocks_daily(start_date, end_date):
    all_data = []
    for index, row in stock_list.iterrows():
        ts_code = row['ts_code']
        try:
            df = pro.daily(ts_code=ts_code, start_date=start_date, end_date=end_date)
            all_data.append(df)
            print(f"已获取 {ts_code} 的数据")
        except Exception as e:
            print(f"获取 {ts_code} 数据失败: {e}")
    return pd.concat(all_data, ignore_index=True)

print("正在获取所有股票的日线数据...")
all_stocks_data = get_all_stocks_daily(start_date, end_date)

# 检查是否有缺失值并清理数据
print("检查数据完整性...")
print(all_stocks_data.isnull().sum())
all_stocks_data.dropna(inplace=True)

# 基本统计分析
print("生成基本统计表...")
basic_stats = all_stocks_data.describe()
basic_stats.to_csv('basic_statistics.csv')
print(basic_stats)

# 按股票分组统计
print("按股票分组统计...")
grouped_stats = all_stocks_data.groupby('ts_code').agg({
    'close': ['mean', 'std', 'min', 'max'],  # 收盘价的统计
    'vol': ['sum', 'mean'],                  # 成交量的统计
})
grouped_stats.to_csv('grouped_statistics.csv')
print(grouped_stats)

# 计算涨跌幅分布
print("计算涨跌幅分布...")
all_stocks_data['pct_change'] = all_stocks_data.groupby('ts_code')['close'].pct_change()
pct_change_stats = all_stocks_data['pct_change'].describe()
pct_change_stats.to_csv('pct_change_statistics.csv')
print(pct_change_stats)

# 找出成交额最高的股票
print("找出成交额最高的股票...")
top_active_stocks = all_stocks_data.groupby('ts_code')['amount'].sum().nlargest(10)
top_active_stocks.to_csv('top_active_stocks.csv')
print(top_active_stocks)

# 数据可视化
print("绘制可视化图表...")

# (1) 涨跌幅分布直方图
plt.figure(figsize=(10, 6))
plt.hist(all_stocks_data['pct_change'].dropna(), bins=50, color='blue', alpha=0.7)
plt.title('Distribution of Daily Price Changes')
plt.xlabel('Percentage Change (%)')
plt.ylabel('Frequency')
plt.grid(True)
plt.savefig('pct_change_distribution.png')  # 保存图片
plt.show()

# (2) 成交额最高的股票柱状图
plt.figure(figsize=(10, 6))
top_active_stocks.plot(kind='bar', color='green', alpha=0.7)
plt.title('Top 10 Active Stocks by Total Amount')
plt.xlabel('Stock Code')
plt.ylabel('Total Amount (CNY)')
plt.grid(True)
plt.savefig('top_active_stocks.png')  # 保存图片
plt.show()

print("数据分析和可视化完成！")